package com.ly.lw.styledo.utils;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.RadioGroup;

import com.ly.lw.styledo.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by sks on 15-7-4.
 */
public class FragmentTableUtils implements RadioGroup.OnCheckedChangeListener {
    private List<Fragment> fragments;
    private RadioGroup rgs;
    private FragmentManager fragmentManager;
    private int fragmentContentId;  //acticity中要被替换的区域
    private int currentTab; // 当前Tab页面索引

    public FragmentTableUtils(FragmentManager fragmentManager, ArrayList<Fragment> fragments, int main_fragment, RadioGroup rgs) {
        this.fragments = fragments;
        this.rgs = rgs;
        this.fragmentManager = fragmentManager;
        fragmentContentId = main_fragment;

        //默认显示第一页内容
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.add(fragmentContentId,fragments.get(0));
        ft.commit();
        rgs.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        for (int i = 0; i < rgs.getChildCount(); i++) {
            if (rgs.getChildAt(i).getId() == checkedId) {
                Fragment fragment = fragments.get(i);
                FragmentTransaction ft =obtainFragmentTransaction(i);
                getCurrentFragment().onStop();
                if (fragment.isAdded()) {
                    fragment.onStart();

                }else{
                    ft.add(fragmentContentId,fragment);
                    ft.commit();
                }

                showTab(i);

            }

        }
    }

    private void showTab(int idx) {
        for (int i = 0; i < fragments.size() ; i++) {
            Fragment fragment = fragments.get(i);
            FragmentTransaction ft = obtainFragmentTransaction(idx);
            if(idx ==i){
                ft.show(fragment);
            }else {
                ft.hide(fragment);
            }
            ft.commit();
        }

        currentTab = idx;

    }


    public int getCurrentTab() {
        return currentTab;
    }

    private Fragment getCurrentFragment() {
        return fragments.get(currentTab);

    }


    /**
     * 获取一个带动画的FragmentTransaction
     *
     * @param index
     * @return
     */
    private FragmentTransaction obtainFragmentTransaction(int index) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        // 设置切换动画
        if (index > currentTab) {
            ft.setCustomAnimations(R.anim.slide_left_in, R.anim.slide_left_out);
        } else {
            ft.setCustomAnimations(R.anim.slide_right_in, R.anim.slide_right_out);
        }
        return ft;


    }
}
